package com.yihaodian.search.facet.merger.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;

import com.yihaodian.api.search.facet.FacetNode;
import com.yihaodian.api.search.facet.FacetResult;
import com.yihaodian.api.search.facet.SearchFacetSpec;
import com.yihaodian.search.facet.merger.FacetMerger;

public class DefaultMerger extends FacetMerger {

	/**
	 * Just merge the facet result, do not sort.
	 */
	@Override
	public FacetResult merge(List<FacetResult> facetResults,
			SearchFacetSpec spec) {
		if (facetResults == null) {
			return null;
		}
		
		Map<String, Long> nodeMap = new HashMap<String, Long>();
		long tmp;
		for (FacetResult facet : facetResults) {
			for (FacetNode node : facet.nodes) {
				if (nodeMap.containsKey(node.label)) {
					tmp = nodeMap.get(node.label) + node.value;
					nodeMap.remove(node.label);
					nodeMap.put(node.label, tmp);
				} else {
					nodeMap.put(node.label, node.value);
				}
			}
		}
		List<FacetNode> results = new ArrayList<FacetNode>(nodeMap.size());
		for (Entry<String, Long> entry : nodeMap.entrySet()) {
			String label = entry.getKey();
			FacetNode node = new FacetNode(label, entry.getValue());
			results.add(node);
		}
		
		FacetResult facetResult = new FacetResult();
		facetResult.setNodes(results);
		return  facetResult;
	}

}
